package cn.cheqi.recovery.api.upload;

import cn.cheqi.recovery.api.dto.DataGridView;
import cn.cheqi.recovery.api.utils.AliyunOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class UploadService {

    //允许上传的图片格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    //允许上传的最大字节数
    private static final Integer MAX_UPLOAD_SIZE = 2097152;

    @Autowired
    private AliyunOssUtil aliyunOssUtil;


    /**
     * 上传图片服务方法
     * @param file
     * @return
     */
    public DataGridView uploadImg(MultipartFile file,String folderType){
        //判断图片是否为空
        if (file.getSize() == 0){
            return new DataGridView(1,"不得上传空文件","");
        }

        //校验图片的格式
        //获取图片的后缀
        String picSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        boolean flag = false;
        for (String type : IMAGE_TYPE) {
            if (picSuffix.equals(type)){
                flag = true;
                break;
            }
        }
        if (flag == false){
            return new DataGridView(1,"图片格式不符合要求","");
        }

        //判断图片是否大于2MB
        if (file.getSize() >= MAX_UPLOAD_SIZE){
            return new DataGridView(1,"上传文件不得超过2MB","");
        }

        //否则上传
        String result = null;
        String fileName = aliyunOssUtil.reName(file.getOriginalFilename(),folderType);
        try {
            InputStream inputStream = file.getInputStream();
            result = aliyunOssUtil.uploadInputStream(inputStream, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new DataGridView(0,"图片上传成功",result);
    }
}
